
import java.io.Serializable;

/**
 * The Packet class
 *
 * @author  Jill San Luis
 */
public class Packet implements Serializable{

    private static final String DELIMITER = "::";
    private PacketType type;
    private PacketAction action;
    private String srcIP;
    private int srcPort = -1;
    private int peerID = -1;

//    private String dstIP;
//    private int dstPort = -1;

    /**
     * Creates a new instance of Packet.
     */
    public Packet(String ip, int port, int peerID, PacketType type, PacketAction action) {
        this.srcIP = ip;
        this.srcPort = port;
        this.peerID = peerID;
        this.type = type;
        this.action = action;
    }


    

    /**
     * @return the type
     */
    public PacketType getType() {
        return type;
    }

    /**
     * @return the action
     */
    public PacketAction getAction() {
        return action;
    }

    /**
     * @return the srcIP
     */
    public String getIp() {
        return srcIP;
    }

    /**
     * @return the srcPort
     */
    public int getPort() {
        return srcPort;
    }

      /**
     * @return the peerID
     */
    public int getPeerID() {
        return peerID;
    }
    
    public String compress(){

        if(srcIP == null || srcPort <0 || getPeerID() <0 || action== null || type == null ){
            return null;
        }

        return srcIP + DELIMITER + srcPort + DELIMITER + getPeerID() + DELIMITER +  type + DELIMITER + action;
    }

    public static Packet decompress(String packet){

        Packet p = null;

        String[] tokens = packet.split(DELIMITER);

        if(tokens.length == 5){
            try{
            String sIP = tokens[0];
            int sPort = Integer.parseInt(tokens[1]);
            int pID = Integer.parseInt(tokens[2]);
            PacketType pt = PacketType.getPacketType(Integer.parseInt(tokens[3]));
            PacketAction a = PacketAction.getPacketAction(Integer.parseInt(tokens[4]));
            p = new Packet(sIP, sPort, pID, pt, a);
            }
            catch(NumberFormatException nfe){
                // bad packet format
                // do nothing!
            }
        }

        return p;
    }

  
    
    
}
